<template>
	<view>
		<view class="form_box">
			<AddForm ref="addFormRef"></AddForm>
		</view>
		<view class="content">
			<up-toast ref="uToastRef"></up-toast>
			<PicEdit @clip-img="clipImg"></PicEdit>
			<view class="text_show" ref="textShow" v-show="textBoxShow">
				<rich-text :nodes="htmlContent"></rich-text>
			</view>
		</view>
	</view>
</template>

<script setup>
import { ref } from 'vue'
import { onReady } from '@dcloudio/uni-app'
import AddForm from './Form.vue'
import PicEdit from './PicEdit.vue'
// #ifdef APP || APP-ANDROID
// 组件丢失问题处理
import UpToast from '@/uni_modules/uview-plus/components/u-toast/u-toast.vue'
// #endif
const textShow = ref(null)
const uToastRef = ref(null)
const addFormRef = ref(null)
const textBoxShow = ref(false)
const htmlContent = ref('')

// 裁剪后的图片事件
const clipImg = imgData => {
	// console.log(imgData,imgData.base64)
	if(imgData.base64){
		getOcrText(imgData.base64)
	}else {
		showFailToast('图片出错,请重新上传');
	}
}
// 处理返回的数据在页面显示
const formatPairs = (arr) => {
  if (!Array.isArray(arr) || arr.length === 0) {
    throw new Error('输入必须是一个长度>1的数组');
  }

  let result = '';
  for (let i = 0; i < arr.length; i += 2) {
    const key = arr[i];
    const value = arr[i + 1];
    if (typeof value === 'number' || !isNaN(Number(value))) {
      result += `${key}:  ${value}<br />`;
    } else {
      result += `${key}${value}<br />`;
    }
  }
  return result;
}
// 获取识别出的数据
const getOcrText = (pic)=>{
	uToastRef.value.show({
		type: "loading",
		title: "识别中...",
		duration: -1,
		message: "正在识别"
	})
	uni.request({
	    url: 'http://0.0.0.0:3000/', //仅为示例，并非真实接口地址。
		method: 'POST',
	    data: {"ImageBase64":pic},
	    success: (res) => {
			textBoxShow.value = true
			if(textShow.value.$el){
				textShow.value.$el.innerHTML = formatPairs(res.data.textDetections)
			} else{
				htmlContent.value = formatPairs(res.data.textDetections)
			}
			console.log(res.data);
			addFormRef.value.setPicData(res.data.textDetections)
			if(uToastRef.value) uToastRef.value.hide()
	    },
		fail() {
			if(uToastRef.value.isShow) uToastRef.value.hide()
			uToastRef.value.show({
				type: "error",
				title: "识别失败",
				duration: 2000,
				message: "识别失败请重新尝试"
			})
		}
	});
}

</script>

<style>
.content {
	padding-top: 0px;
}
.text_show {
	margin-top: 10rpx;
	background: rgba(0, 0, 0, .1);
	padding: 10rpx;
	border-radius: 8rpx;
}
</style>